<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>推荐系统查询</title>

    <!-- 引入 Chart.js 及时间适配器 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

    <style>
        :root {
            --bg-color: #f9f9f9;
            --card-bg: #ffffff;
            --primary-color: #007bff;
            --text-color: #333;
            --border-radius: 8px;
            --box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease-in-out;
        }

        body {
            font-family: Arial, sans-serif;
            margin: 40px;
            background-image: url("/images/1.jpg");
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
        }

        /* 添加全屏半透明遮罩层 */
        body::before {
            content: "";
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.5);
            z-index: -1;
        }

        h2 {
            text-align: center;
            margin-bottom: 30px;
        }

        .container {
            display: flex;
            gap: 40px;
            flex-wrap: wrap;
            justify-content: center;
        }

        .card {
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
            flex: 1 1 300px;
        }

        input,
        button {
            padding: 10px;
            margin-top: 5px;
            width: 100%;
            box-sizing: border-box;
        }

        button {
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
        }

        button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }

        ul {
            list-style-type: none;
            padding-left: 0;
            margin-top: 10px;
        }

        li {
            margin-bottom: 6px;
            padding: 6px 10px;
            background-color: #f0f0f0;
            border-radius: 4px;
        }
    </style>
</head>
<body>

<h2>协同过滤推荐查询</h2>

<div class="container">
    <!-- 用户名查推荐商品 -->
    <div class="card">
        <h3>通过用户ID查推荐商品</h3>
        <input type="text" id="userNameInput" placeholder="输入用户名" />
        <button onclick="searchUser()">查询</button>
        <ul id="userResults"></ul>
    </div>

    <!-- 商品名查相似商品 -->
    <div class="card">
        <h3>通过商品ID查相似商品</h3>
        <input type="text" id="itemNameInput" placeholder="输入商品名" />
        <button onclick="searchItem()">查询</button>
        <ul id="itemResults"></ul>
    </div>

    <!-- 商品名查适合用户 -->
    <div class="card">
        <h3>通过商品名查适合用户</h3>
        <input type="text" id="itemForUserInput" placeholder="输入商品名" />
        <button onclick="searchUserByItem()">查询</button>
        <ul id="userByItemResults"></ul>
    </div>
</div>

<!-- 新增：动态折线图 -->
<div class="card" style="width: 100%; max-width: 1200px; margin: 40px auto 0 auto;">
    <h3>商品上下架趋势图</h3>
    <canvas id="inOutChart" height="100"></canvas>
</div>

<!-- 在折线图下方添加紫色按钮 -->
<div style="text-align: center; margin-top: 60px;">
    <a href="/realtime-monitor.html">
        <button style="
            background-color: #8e44ad;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;">
            详细实时数据监控
        </button>
    </a>
</div>


<script defer>
    let inOutChart = null;

    function initChart() {
        const ctx = document.getElementById('inOutChart').getContext('2d');
        inOutChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        label: '上架数量',
                        data: [],
                        borderColor: 'red',
                        fill: false,
                        tension: 0.1
                    },
                    {
                        label: '下架数量',
                        data: [],
                        borderColor: 'blue',
                        fill: false,
                        tension: 0.1
                    }
                ]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { display: true },
                    tooltip: {
                        mode: 'index',
                        intersect: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return value.toLocaleString();
                            }
                        }
                    },
                    x: {
                        type: 'linear', // 改为线性坐标轴
                        title: {
                            display: true,
                            text: '近30秒上下架（两秒一组）'
                        },
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }

    function fetchAndUpdateChart() {
        fetch('http://localhost:8080/api/recommend/inout/latest')
            .then(res => {
                if (!res.ok) throw new Error("网络错误");
                return res.json();
            })
            .then(data => {
                if (!data || !Array.isArray(data)) return;

                // 1. 取最后15条数据，并按时间升序排序（旧 → 新）
                let latestData = data.slice(-15);
                latestData.sort((a, b) => new Date(a.updateTime) - new Date(b.updateTime));

                // 2. 【核心】不要反转整个数组！保持顺序为「旧 → 新」
                // latestData = [...latestData].reverse(); ← 删除这行！

                const labels = latestData.map((_, index) => index); // [0,1,...,14]
                const totalIn = latestData.map(item => item.totalIn);
                const totalOut = latestData.map(item => item.totalOut);

                inOutChart.data.labels = labels;
                inOutChart.data.datasets[0].data = totalIn;
                inOutChart.data.datasets[1].data = totalOut;
                inOutChart.update();
            })
            .catch(err => console.error("获取图表数据失败", err));
    }



    // 页面加载完成后初始化图表 + 定时刷新
    window.addEventListener('DOMContentLoaded', () => {
        initChart();
        fetchAndUpdateChart(); // 初始加载一次
        setInterval(fetchAndUpdateChart, 2000); // 每2秒刷新一次
    });
</script>
<script>
    function fetchAndDisplay(url, resultId, type) {
        const results = document.getElementById(resultId);
        results.innerHTML = "<li>加载中...</li>";

        fetch(url)
            .then(res => {
                if (!res.ok) throw new Error("网络错误");
                return res.json();
            })
            .then(data => {
                results.innerHTML = "";
                if (!data || data.length === 0) {
                    results.innerHTML = "<li>没有结果</li>";
                    return;
                }

                data.forEach(item => {
                    let text = "";

                    if (type === "recommendation") {
                        const score = item.score !== undefined ? item.score : item.similarity;
                        const formattedScore = parseFloat(score).toFixed(3);
                        text = `${item.gname} - ${formattedScore}`;
                    } else if (type === "similarItems") {
                        const formattedScore = parseFloat(item.similarity).toFixed(3);
                        text = `${item.gname} - ${formattedScore}`;
                    } else if (type === "userByItem") {
                        const formattedScore = parseFloat(item.score).toFixed(3);
                        text = `${item.name} - ${item.age}岁 - ${item.gender} - ${formattedScore}`;
                    }

                    const li = document.createElement("li");
                    li.textContent = text;
                    results.appendChild(li);
                });
            })
            .catch(err => {
                console.error(err);
                results.innerHTML = "<li>出错了，请稍后再试</li>";
            });
    }

    function searchUser() {
        const input = document.getElementById("userNameInput");
        const name = encodeURIComponent(input.value.trim());
        const btn = document.querySelector("[onclick='searchUser()']");

        if (!name) return alert("请输入用户名");
        btn.disabled = true;

        fetchAndDisplay(`http://localhost:8080/api/recommend/user/name?name=${name}`, "userResults", "recommendation")
            .finally(() => btn.disabled = false);
    }

    function searchItem() {
        const input = document.getElementById("itemNameInput");
        const gname = encodeURIComponent(input.value.trim());
        const btn = document.querySelector("[onclick='searchItem()']");

        if (!gname) return alert("请输入商品名");
        btn.disabled = true;

        fetchAndDisplay(`http://localhost:8080/api/recommend/item/gname?gname=${gname}`, "itemResults", "similarItems")
            .finally(() => btn.disabled = false);
    }

    function searchUserByItem() {
        const input = document.getElementById("itemForUserInput");
        const gname = encodeURIComponent(input.value.trim());
        const btn = document.querySelector("[onclick='searchUserByItem()']");

        if (!gname) return alert("请输入商品名");
        btn.disabled = true;

        fetchAndDisplay(`http://localhost:8080/api/recommend/user/by-gname?gname=${gname}`, "userByItemResults", "userByItem")
            .finally(() => btn.disabled = false);
    }
</script>

</body>
</html>
